package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.tools.TimeWindowS;
import com.sxm.yiwei.utils.InternetAddressUtis;


import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ApplyHopeStoreActivity extends BaseActivity implements View.OnClickListener {

    private ImageView applyback;
    private Button applybegin;
    private Button applyover;
    private TextView begintime;
    private TextView overtime;
    private ImageView applyimg1,applyimg2,applyimg3;
    private Button applysure;
    private BaseIntents baseIntents;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private static final int PHOTO_TEXT = 3022;
    private static final int CAMERA_WITH_DATA = 3023;
    private List<String> imglist;
    private Bitmap photo;
    private String path1;
    private int currentIndex;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private EditText inquestintro;
    String beginTime = null;
    String overTime = null;
    private String shopid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_hope_store);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");
        shopid = sharedPreferences.getString("shopid", "2");
        initApply();
        baseIntents = new BaseIntents();
        imglist = new ArrayList();
    }

    private void initApply() {
        applyback = (ImageView) findViewById(R.id.hopestore_applyback);
        applybegin = (Button) findViewById(R.id.hopestore_applybegin);
        applyover = (Button) findViewById(R.id.hopestore_applyover);
        begintime = (TextView) findViewById(R.id.hopestore_applybegin);
        overtime = (TextView) findViewById(R.id.hopestore_applyover);
        applyimg1 = (ImageView) findViewById(R.id.apply_storeimg1);
        applyimg2 =(ImageView) findViewById(R.id.apply_storeimg2);
        applyimg3 =(ImageView) findViewById(R.id.apply_storeimg3);
        applysure = (Button) findViewById(R.id.applystore_sure);
        inquestintro = (EditText) findViewById(R.id.apply_questintro);
        applyback.setOnClickListener(this);
        applyover.setOnClickListener(this);
        applybegin.setOnClickListener(this);
        applyimg1.setOnClickListener(this);
        applyimg2.setOnClickListener(this);
        applyimg3.setOnClickListener(this);
        applysure.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        String questintro = inquestintro.getText().toString().trim();
        switch (v.getId()){
            case R.id.hopestore_applyback:
                finish();
                break;
            case R.id.hopestore_applybegin:
                final TimeWindowS beginpop = new TimeWindowS(ApplyHopeStoreActivity.this);
                beginpop.showAtLocation(findViewById(R.id.apply_view), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                beginpop.setTimeOnClick(new TimeWindowS.TimeOnClick() {
                    @Override
                    public void onClickCancel() {
                        beginpop.dismiss();
                    }

                    @Override
                    public void onClickSure(String s) {

                        begintime.setText(s);
                        beginpop.dismiss();
                        beginTime= s;

                    }
                });
                break;
            case R.id.hopestore_applyover:
                final TimeWindowS overpop = new TimeWindowS(ApplyHopeStoreActivity.this);
                overpop.showAtLocation(findViewById(R.id.apply_view), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                overpop.setTimeOnClick(new TimeWindowS.TimeOnClick() {
                    @Override
                    public void onClickCancel() {
                        overpop.dismiss();
                    }
                    @Override
                    public void onClickSure(String s) {
                        overtime.setText(s);
                        overpop.dismiss();
                        overTime= s;
                    }
                });
                break;
            case R.id.apply_storeimg1:
                currentIndex = 1;
                doPickPhotoAction();
                break;
            case R.id.apply_storeimg2:
                currentIndex = 2;
                doPickPhotoAction();
                break;
            case R.id.apply_storeimg3:
                currentIndex = 3;
                doPickPhotoAction();
                break;
            case R.id.applystore_sure:
                Toast.makeText(this, "提交申请", Toast.LENGTH_SHORT).show();
                if (beginTime==null){
                    Toast.makeText(this, "请选择开始时间", Toast.LENGTH_SHORT).show();

                }else {
                    if (overTime==null){
                        Toast.makeText(this, "请选择结束时间", Toast.LENGTH_SHORT).show();
                    }else {
                        if (!TextUtils.isEmpty(questintro)){
                            if (imglist.size()==0){
                                Toast.makeText(this, "请选择申请图片", Toast.LENGTH_SHORT).show();
                            }else {
                                applyQuestStore(questintro);
                            }
                        }else {
                            Toast.makeText(this, "请输入申请原因", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                break;
        }
    }
        // 提交爱心店铺申请
    private void applyQuestStore(String questintro) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETAPPLYLOVESTORE);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("applyExcuse",questintro);
        params.addBodyParameter("applyTime",beginTime);
        params.addBodyParameter("applyEndTime",overTime);
       // params.addBodyParameter("shopId", "dc69bdff-a1f2-11e7-83ac-000c2988fecb");
        for (int i = 0; i < imglist.size(); i++) {
            params.addBodyParameter("applyavatar",new File(imglist.get(i)));
        }
        params.setMultipart(true);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject object = JSON.parseObject(result);
                String status = object.getString("status");
                if (status.equals("1")){
                    Toast.makeText(ApplyHopeStoreActivity.this, "申请已提交，请等待审核", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 申请店铺--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                Bitmap photo = data.getParcelableExtra("data");
                String s = CropPictures.saveBitmapFile(photo, new BaseIntents().getPhotoFileName());
                imglist.add(s);
                switch (imglist.size()){
                    case 0:

                        break;
                    case 1:
                        applyimg2.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        applyimg3.setVisibility(View.VISIBLE);
                        break;
                }

                if (currentIndex==1){
                    applyimg1.setImageBitmap(photo);
                }else if (currentIndex==2){
                    applyimg2.setImageBitmap(photo);
                }else if (currentIndex==3){
                    applyimg3.setImageBitmap(photo);
                }
            }

            break;
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);
                break;
            }

            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;

        }

    }

}
